package lib.base

import BaseFrag
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import androidx.annotation.StringRes
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ToastUtils
import lib.base.mix.DefaultVm

/**
 * @author: luoXiong
 * @date: 2019/5/23 10:26
 * @version: 1.0
 * @desc:  BaseRvRefreshManager
 */
@SuppressLint("StaticFieldLeak")
object DefaultManager : IManager<DefaultVm>() {}


//abstract class IManager<F : BaseFrag<*,*,*>, VM : ViewModel> {
abstract class IManager<VM : ViewModel> {
    private lateinit var mAct: FragmentActivity
    private lateinit var mModel: VM
    private var mFrag: Fragment? = null

    // 创建Manager
    fun <M : IManager<VM>, VM : ViewModel> createManager(managerClass: Class<M>, modelClass: Class<VM>): M {
        val manager = managerClass.newInstance()
        manager.setFragment(mFrag)
            .setActivity(getAct())
            .setViewModel(ViewModelProvider(getAct()).get(modelClass))
        return manager
    }

    fun getVm(): VM {
        return mModel
    }

    fun getBaseVm(): BaseViewModel {
        return mModel as BaseViewModel
    }

    fun setActivity(activity: FragmentActivity): IManager<VM> {
        mAct = activity
        return this
    }

    fun setViewModel(model: VM): IManager<VM> {
        mModel = model
        return this
    }

    fun setFragment(frag: Fragment?): IManager<VM> {
        mFrag = frag
        return this
    }

    fun <T> getFrag(clazz: Class<T>): T? {
        return mFrag as? T
    }

    fun getAct(): FragmentActivity {
        return mAct
    }

    fun requireActivity(): Activity {
        return mAct
    }

    fun getFragAct(): FragmentActivity {
        if (mAct is FragmentActivity) {
            return mAct as FragmentActivity
        }
        return mFrag!!.requireActivity()
    }

    fun getFrag(): Fragment {
        return mFrag!!
    }

    fun getBaseFragCanNull(): BaseFrag<*, *, *>? {
        return mFrag as? BaseFrag<*, *, *>
    }


    fun getBaseFrag(): BaseFrag<*, *, *> {
        return mFrag as BaseFrag<*, *, *>
    }

    fun finish() {
        mAct.finish()
    }

    open fun onDestroy() {

    }

    fun showToast(msg: String?) {
        msg ?: return
        ToastUtils.showShort(msg)
    }

    fun showToast(@StringRes resId: Int) {
        ToastUtils.showShort(resId)
    }

    open fun finishAndSetResultOk(intent: Intent? = null) {
        getAct().setResult(Activity.RESULT_OK, intent)
        finish()
    }


}